package com.emex.app.web;

import com.emex.app.shared.data.User;
import com.emex.app.shared.data.UserExample;
import com.emex.app.shared.persistance.UserMapper;
import com.emex.app.shared.ws.AuthenticationWebService;
import java.util.List;
import javax.ejb.Stateless;
import javax.jws.WebService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

@WebService(serviceName = "AuthenticationWS", portName = "AuthenticationWSPort", targetNamespace = "http://emex.com/Authentication")
@Stateless(name = "AuthenticationWS")
public class AuthenticationWS extends SpringBeanAutowiringSupport
        implements AuthenticationWebService {

    @Autowired
    private UserMapper userMapper;

    private static final Logger logger
            = LoggerFactory.getLogger(AuthenticationWS.class);

    /**
     * Simple operation to check authentication parameters
     *
     * @return
     */
    @Override
    public User authenticate(String username, String password) {
        logger.info("User :: " + username + " is trying to login...");
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username)
                .andPasswordEqualTo(password);
        List<User> users = userMapper.selectByExample(example);
        if (null == users || users.isEmpty() || users.size() > 1) {
            logger.error("User :: " + username + " is not authenticated");
            return null;
        } else {
            logger.info("Authenticated user :: " + username);
            return users.get(0);
        }
    }

    @Override
    public int deleteUserByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public User insertUser(User record) {
        userMapper.insert(record);
        return record;
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectByExample(null);
    }

    @Override
    public User updateUserByPrimaryKey(User record) {
        userMapper.updateByPrimaryKey(record);
        return record;
    }

    @Override
    public User selectUserByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }
}
